const path = require('path')
const webpack = require('webpack')
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const GitRevision = new GitRevisionPlugin()
const buildDate = JSON.stringify(new Date().toLocaleString())
const packageObj = require('./package.json')
const Timestamp = new Date().getTime()
function resolve (dir) {
  return path.join(__dirname, dir)
}
// check Git
function getGitHash () {
  try {
    return GitRevision.version()
  } catch (e) {}
  return 'unknown'
}

const UselessFile = require('useless-files-webpack-plugin')

const isProd = process.env.NODE_ENV === 'production'

const assetsCDN = {
  // webpack build externals
  externals: {},
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: []
}

// vue.config.js
const vueConfig = {
  configureWebpack: {
    resolve: {
      extensions: ['.js', '.vue', '.json'],
      alias: {
        '@@': resolve('src')
      }
    },
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        APP_VERSION: `"${packageObj.version}"`,
        GIT_HASH: JSON.stringify(getGitHash()),
        BUILD_DATE: buildDate
      })
    ],
    // if prod, add externals
    externals: isProd ? assetsCDN.externals : {},
    devtool: process.env.NODE_ENV === 'development' ? 'source-map' : undefined,
    output: {
      // 把子应用打包成 umd 库格式
      library: `${packageObj.name}`,
      libraryTarget: 'umd',
      jsonpFunction: `webpackJsonp_${packageObj.name}`,
      filename: `js/[name].js?time=${Timestamp}`,
      chunkFilename: `js/[name].js?time=${Timestamp}`
    },
    optimization: {
      splitChunks: {
        cacheGroups: {
          crec: {
            chunks: 'all',
            name: `crec-ui`,
            test: /[\\/]crec-ui[\\/]/,
            priority: 0
          },
          common: {
            chunks: 'all',
            test: /[\\/]src[\\/]js[\\/]/,
            name: 'common',
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 60
          },
          styles: {
            name: 'styles',
            test: /\.(sa|sc|c)ss$/,
            chunks: 'all',
            enforce: true
          },
          runtimeChunk: {
            name: 'manifest'
          }
        }
      }
    }
  },

  chainWebpack: (config) => {
    config.resolve.alias.set('@$', resolve('src'))

    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: `assets/[name].[ext]?time=${Timestamp}`
      })

    // if prod is on

    if (isProd) {
      // assets require on cdn
      config.plugin('html').tap((args) => {
        args[0].cdn = assetsCDN
        return args
      })
    }

    config.plugin('uselessFile').use(
      new UselessFile({
        root: path.resolve(__dirname, './src'), // 项目目录
        out: './fileList.json', // 输出文件列表
        clean: false, // 是否删除文件,
        exclude: /node_modules/ // 排除文件列表
      })
    )
  },

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // less vars，customize ant design theme
        },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true
      }
    },
    sourceMap: !isProd,
    extract: {
      // 打包后css文件名称添加时间戳
      filename: `css/[name].css?time=${Timestamp}`,
      chunkFilename: `css/[name].css?time=${Timestamp}`
    }
  },

  devServer: {
    // development server port 8001
    port: process.env.VUE_APP_PORT,
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    proxy: {
      // 权限服务代理
      '/crec-authority-web': {
        // target: 'https://dev-hr.crec.cn/staff/api',
        target: 'https://dev-hr.crec.cn/gateway',
        ws: false,
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
          [`(^.*/api)`]: ''
        }
      },
      // 人事服务代理
      '/hr-basic-staff': {
        target: 'https://dev-hr.crec.cn/staff/api',
        ws: false,
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
          [`(^.*/api)`]: ''
        }
      },
      // 招聘服务代理
      [process.env.VUE_APP_API_RECRUIT_SERVICE_URL]: {
        target: 'http://10.7.235.148:18135',
        // target: 'https://dev-hr.crec.cn/gateway',
        ws: false,
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
          [`(^.*${process.env.VUE_APP_API_BASE_URL})`]: ''
        }
      },
      // 请求网络的代理路径
      [process.env.VUE_APP_API_BASE_URL]: {
        target: process.env.VUE_APP_HOST_URL,
        ws: false,
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
          [`(^.*${process.env.VUE_APP_API_BASE_URL})`]: ''
        }
      }
    }
  },
  // disable source map in production
  productionSourceMap: false,
  lintOnSave: undefined,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: ['crec-common', 'crec-business-component', 'import-html-entry', 'crypto-js'],
  publicPath: process.env.VUE_APP_PUBLIC_PATH || '/'
}
if (isProd) {
  vueConfig.configureWebpack.plugins.push(
    new CompressionWebpackPlugin({
      test: /\.js$|\.html$|\.css$/,
      threshold: 10240, // 超过10kb压缩
      deleteOriginalAssets: true
    })
  )
}
module.exports = vueConfig
